from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Optional, List

from ..core.database import get_db
from ..utils.deps import get_current_user
from ..models.user import User
from ..schemas.note import NoteCreate, NoteUpdate, NoteResponse, NoteListResponse
from ..services.note_service import NoteService

router = APIRouter(prefix="/notes", tags=["笔记"])


@router.get("", response_model=NoteListResponse)
async def get_notes(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    notebook_id: Optional[int] = None,
    tag_id: Optional[int] = None,
    is_pinned: Optional[bool] = None,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取笔记列表"""
    notes, total = NoteService.get_notes(
        user_id=current_user.id,
        db=db,
        skip=skip,
        limit=limit,
        notebook_id=notebook_id,
        tag_id=tag_id,
        is_pinned=is_pinned
    )
    return {"total": total, "notes": notes}


@router.get("/search", response_model=List[NoteResponse])
async def search_notes(
    keyword: str = Query(..., min_length=1),
    limit: int = Query(50, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """搜索笔记"""
    notes = NoteService.search_notes(keyword, current_user.id, db, limit)
    return notes


@router.get("/{note_id}", response_model=NoteResponse)
async def get_note(
    note_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取笔记详情"""
    note = NoteService.get_note(note_id, current_user.id, db)
    return note


@router.get("/{note_id}/recommendations", response_model=List[NoteResponse])
async def get_recommended_notes(
    note_id: int,
    limit: int = Query(5, ge=1, le=20),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取推荐笔记"""
    notes = NoteService.get_recommended_notes(note_id, current_user.id, db, limit)
    return notes


@router.post("", response_model=NoteResponse, status_code=201)
async def create_note(
    note_data: NoteCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建笔记"""
    note = NoteService.create_note(note_data, current_user.id, db)
    return note


@router.put("/{note_id}", response_model=NoteResponse)
async def update_note(
    note_id: int,
    note_data: NoteUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新笔记"""
    note = NoteService.update_note(note_id, note_data, current_user.id, db)
    return note


@router.delete("/{note_id}", status_code=204)
async def delete_note(
    note_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除笔记"""
    NoteService.delete_note(note_id, current_user.id, db)
    return None

